package com.bnz.service.impl;

import com.bnz.mapper.ClassesMapper;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.Classes;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import com.bnz.util.MyBatisUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentServiceImpl implements StudentService {


    @Override
    public List<Student> findAll() {
        try (SqlSession session = MyBatisUtil.getSession()) {
            //1.1 得到Mapper对象
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            ClassesMapper classesMapper = session.getMapper(ClassesMapper.class);
            //1.2 查询所有学生
            List<Student> studs = mapper.findAll();
            //1.3 建立学生与班级的绑定关系
            for (Student stud : studs) {
                Classes classes = classesMapper.findById(stud.getCid());
                stud.setCname(classes.getCname());
            }
            //1.4 返回
            return studs;

        }
    }

    @Override
    public PageResult<Student> findByPage(int page, int pagesize) {
        //1\开始分页
        //2.1 开始分页
        PageHelper.startPage(page,pagesize);
        //2.2 开始查询
        try(SqlSession session = MyBatisUtil.getSession()){
            //2.3 得到Mapper对象
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            ClassesMapper classesMapper = session.getMapper(ClassesMapper.class);
            //2.4 查询学生列表
            List<Student> students = mapper.findAll();
            //2.5 建立学生与班级的绑定关系
            for (Student stud : students) {
                Classes classes = classesMapper.findById(stud.getCid());
                stud.setCname(classes.getCname());
            }
            //2.6 转换对象为PageInfo
            Page<Student> pageInfo = (Page<Student>) students;
            //1.4 返回
            return new PageResult<>(pageInfo.getTotal(),pageInfo.getResult());

        }

    }
}

